package com.base.cn.platform.os.service.statistics.ua;

import com.base.cn.platform.os.common.mybatis.BaseBiz;
import com.base.cn.platform.os.common.utils.DateUtils;
import com.base.cn.platform.os.common.utils.ObjectUtils;
import com.base.cn.platform.os.dao.statistics.ua.ZStatisticsActiveUserCountDao;
import com.base.cn.platform.os.entity.statistics.ua.ZStatisticsActiveUserCount;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 用户活跃统计Biz
 *
 * @author s.li
 * @date 2019/04/19
 */
@Service
public class ZStatisticsActiveUserCountBiz extends BaseBiz<ZStatisticsActiveUserCount, ZStatisticsActiveUserCountDao> {

    /**
     * 创建用户活跃统计数据
     * @param statisticsActiveUserCountList 数据列表
     */
    public void createActiveUserCount(List<ZStatisticsActiveUserCount> statisticsActiveUserCountList){
        if(ObjectUtils.isNotEmpty(statisticsActiveUserCountList)){
            String timeWhereSql = statisticsActiveUserCountList.stream().map(e-> "DATE_FORMAT(countTime,'%Y-%m-%d')='"+ DateUtils.format(e.getCountTime(),"yyyy-MM-dd")+"'").collect(Collectors.joining(" or "," 1=1 and (",")"));
            List<ZStatisticsActiveUserCount> activeUserCountList = this.find(timeWhereSql,null,null);

            List<ZStatisticsActiveUserCount> updateList = new ArrayList<>();
            List<ZStatisticsActiveUserCount> addList = new ArrayList<>();

            if(ObjectUtils.isNotEmpty(activeUserCountList)){
                Map<String,ZStatisticsActiveUserCount> oldActiveUserCountMap = activeUserCountList.stream().collect(Collectors.toMap(e->DateUtils.format(e.getCountTime(),"yyyy-MM-dd"), e->e));
                Map<String,ZStatisticsActiveUserCount> newActiveUserCountMap = statisticsActiveUserCountList.stream().collect(Collectors.toMap(e->DateUtils.format(e.getCountTime(),"yyyy-MM-dd"), e->e));
                newActiveUserCountMap.forEach((k,v)->{
                    ZStatisticsActiveUserCount oldData = oldActiveUserCountMap.get(k);
                    if(ObjectUtils.isNotEmpty(oldData)){
                        oldData.setUserCount(v.getUserCount());
                        updateList.add(oldData);
                    }else{
                        addList.add(v);
                    }
                });
            }else{
                addList.addAll(statisticsActiveUserCountList);
            }

            if(ObjectUtils.isNotEmpty(addList)){
                this.batchSave(addList);
            }
            if(ObjectUtils.isNotEmpty(updateList)){
                this.updateBatch(updateList);
            }
        }
    }
}
